package com.citicpub_cloud.restfull.utils;/*
 * Copyright 2006-2007 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.ezmorph.MorphException;
import net.sf.ezmorph.object.AbstractObjectMorpher;

/**
 * Morphs a String to a Date.<br>
 * <p>
 * This morpher will iterate through the supplied formats until one succeeds or
 * the default value is returned (if default value is configured).
 * </p>
 *
 * @author Andres Almiray <aalmiray@users.sourceforge.net>
 */
public class DateMorpher extends AbstractObjectMorpher
{

    private static Logger log = LoggerFactory.getLogger(DateMorpher.class);
    //yyyy-MM-dd HH:mm:ss
    private final HashSet<String> patternSets = new HashSet<String>();

    public DateMorpher(String ... patterns){
        if(null!=patterns){
            for(String pattern : patterns){
                if(StringUtils.isNotBlank(pattern)){
                    this.patternSets.add(pattern);
                }
            }
        }else{
        	throw new RuntimeException("日期转换格式字串不能为空");
        }
    }

    public void addPattern( String pattern){
        this.patternSets.add(pattern);
    }

    @Override
    public Class morphsTo() {
        return Date.class;
    }

    @Override
    public Object morph(Object o) {
        if(o==null){
            return null;
        }
        if(o instanceof String){
            String value = ((String) o).trim();
            for(String parrent:patternSets){
                if(value.length() == parrent.length()){
                    SimpleDateFormat sdf = new SimpleDateFormat(parrent);
                    try {
                        return sdf.parse(value);
                    } catch (ParseException e) {
                        log.error("转换日期出错，value:{}, pattern:{}",value,parrent);
                        throw new MorphException( "Unable to parse the date " + value );
                    }
                }
            }
        }
        return o;
    }
}